/*
编程实现服务器端把所有连接过来的客户端套接字存储在列表中，
当客户端程序退出时，服务器端列表删掉该套接。
*/

#include "widget.h"
#include "ui_widget.h"
#include <QTcpSocket>
#include <QMessageBox>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , m_ptcpserver(new QTcpServer(this))
    , clientList()
{
    ui->setupUi(this);
    init_network();

    connect(ui->pushButton, &QPushButton::clicked, this, &Widget::show_client);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::init_network(){
    qDebug() << "start init network";

    if(!m_ptcpserver->listen(QHostAddress("127.0.0.1"), 8099)){
        qDebug() << "init network fail";
        QMessageBox::warning(this, "server listen", "start listen fail...");
        exit(1);
    }else{
        QMessageBox::information(this, "server listen", "start listen success...");
    }

    qDebug() << "init network success";

    connect(m_ptcpserver, &QTcpServer::newConnection, this, &Widget::new_connection);

    return;
}

void Widget::new_connection(){
    QTcpSocket* ptcpsocket = m_ptcpserver->nextPendingConnection();

    QString strclientip = ptcpsocket->peerAddress().toString();
    QString strclientport = QString::number(ptcpsocket->peerPort());
    QMessageBox::information(this, "[server]client connect", "new client connect:" + strclientip + ":" + strclientport);

    clientList.append(ptcpsocket);

    connect(ptcpsocket, &QTcpSocket::disconnected, this, &Widget::dis_connected);

    return;
}

void Widget::dis_connected()
{
    QTcpSocket* ptcpsocket = (QTcpSocket*)sender();

    QString strclientip = ptcpsocket->peerAddress().toString();
    QString strclientport = QString::number(ptcpsocket->peerPort());
    QMessageBox::information(this, "[server]client disconnected", "client disconnected:" + strclientip + ":" + strclientport);


    clientList.removeOne(ptcpsocket);

    ptcpsocket->close();

    return;
}

void Widget::show_client(){

    ui->textEdit->clear();

    for(QTcpSocket* clientSocket : clientList){
        QString strclientip = clientSocket->peerAddress().toString();
        QString strclientport = QString::number(clientSocket->peerPort());
        ui->textEdit->append(strclientip + ":" + strclientport);
    }
}
